import 'dart:io';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterdemo/0demo/multi_image_picker/img_crop_page.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_crop/image_crop.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:path_provider/path_provider.dart';

class ImagePickerTestPage extends StatefulWidget {
  @override
  _ImagePickerTestPageState createState() => _ImagePickerTestPageState();
}

class _ImagePickerTestPageState extends State<ImagePickerTestPage> {
  final ImagePicker _picker = ImagePicker();
  final _imagePath = List<String>();
  final cropKey = GlobalKey<CropState>();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("multi image picker"),
      ),
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              FlatButton(
                child: Text("single image picker"),
                onPressed: () {
                  _singleImagePicker(0);
                },
              ),
              FlatButton(
                child: Text("single image picker camera"),
                onPressed: () {
                  _singleImagePicker(1);
                },
              ),
              FlatButton(
                child: Text("multi image picker"),
                onPressed: () {
                  _pickAssets();
                },
              ),
              Image.file(File(_imagePath.length > 0 ? _imagePath[_imagePath.length - 1] : "")),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _singleImagePicker(int operation) async {
    PickedFile pickedFile;
    if (operation == 0) {
      pickedFile = await _picker.getImage(source: ImageSource.gallery);
    } else if (operation == 1) {
      pickedFile = await _picker.getImage(source: ImageSource.camera);
    }
    print("pickedFile.path == ${pickedFile.path}");
    File originFile = File(pickedFile.path);
    if (!originFile.existsSync()) {
      print("原文件路径不存在！");
      Fluttertoast.showToast(msg: "原文件路径不存在！");
      return;
    }
    final sample = await ImageCrop.sampleImage(
      file: originFile,
      preferredSize: context.size.longestSide.ceil(),
    );
    Navigator.push(context, CupertinoPageRoute(builder: (context) => ImgCropPage(sample: sample)));
  }

  Future<void> _pickAssets() async {
    List<Asset> resultList = List<Asset>();
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 5,
        enableCamera: true,
//        selectedAssets: resultList,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Example App",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      print(e);
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    for (var item in resultList) {
      String path = await _getImageStoragePath();
      print("_getImageStoragePath == $path");

      File file = new File(path);
      //写文件
      var byteData = await item.getByteData();
      await file.writeAsBytes(byteData.buffer.asInt8List(0));
      setState(() {
        print("file path == " + file.absolute.path);
        _imagePath.add(path);
      });
    }
  }

  Future<String> _getImageStoragePath() async {
    var applicationDocumentsDirectory = await getApplicationDocumentsDirectory();
    // only IOS
//    var applicationDocumentsDirectory = await getLibraryDirectory();
    // /data/user/0/top.tupobi.flutterdemo/
//    var applicationDocumentsDirectory = await getApplicationSupportDirectory();
    // /data/user/0/top.tupobi.flutterdemo/cache
//    var applicationDocumentsDirectory = await getTemporaryDirectory();
    var directory = Directory(applicationDocumentsDirectory.path + "/picked_images/");
    await directory.create();
    return directory.path +
        DateTime.now().millisecondsSinceEpoch.toString() +
        Random().nextInt(100).toString() +
        ".png";
  }
}
